package com.birdboot.core;

import com.birdboot.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 该线程的任务是与指定的客户端完成HTTP交互
 * HTTP协议要求一问一答
 * 对此,这里的处理大致分为三步
 * 1:解析请求
 * 2:处理请求
 * 3:发送响应
 */
public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run() {
        try {
            //1解析请求
            HttpServletRequest request = new HttpServletRequest(socket);

            //2处理请求
            String path = request.getUri();
            System.out.println("抽象路径:"+path);
            File baseDir = new File(
                    ClientHandler.class.getClassLoader().getResource(".").toURI()
            );
            File staticDir = new File(baseDir,"static");
            File file = new File(staticDir,path);

            /*
                V6新增内容:
                添加一个分支判断,file对象是否表示的是一个文件, 如果是则将该文件响应给
                浏览器.如果不是应当响应404页面给浏览器
             */
            int statusCode;//状态代码
            String statusReason;//状态描述
            if(file.isFile()){
                statusCode=200;
                statusReason="OK";
            }else{
                statusCode=404;
                statusReason="NotFound";
                file = new File(staticDir,"404.html");
            }


            //3发送响应
            //3.1发送状态行
            //V6改动,按照处理要求发送对应的状态代码和描述
            println("HTTP/1.1"+" "+statusCode+" "+statusReason);
            //3.2发送响应头
            println("Content-Type: text/html");
            println("Content-Length: "+file.length());
            //单独发送回车+换行表达响应头发完了
            println("");

            //3.3发送响应正文
            OutputStream out = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[1024*10];
            int len;
            while((len=fis.read(data))!=-1){
                out.write(data,0,len);
            }
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        } finally {
            //遵循HTTP协议要求,一问一答后与客户端断开连接
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 向客户端发送一行字符串
     */
    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        out.write(line.getBytes(StandardCharsets.ISO_8859_1));
        out.write(13);//单独发送回车符
        out.write(10);//单独发送换行符
    }


}
